package com.ht.medicaltreatment.activity

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.MultiSampleCollectionAdapter
import com.ht.medicaltreatment.bean.Drawblood
import com.ht.medicaltreatment.utils.*
import com.ht.medicaltreatment.view.BloodRemarkDialog
import com.ht.medicaltreatment.view.ReplaceCaiXueDialog
import com.ht.medicaltreatment.viewmodel.SingleViewModel
import com.xgst.lib.utils.showToast
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.*
import java.text.SimpleDateFormat
import java.util.concurrent.TimeUnit

/**
 * 表单列表进来的
 */
class SingleSampleCollectionDetailActivity:BaseActivity(), View.OnClickListener {
    override fun getLayoutId() = R.layout.activity_multi_sample_collection_detail_layout

    private lateinit var adapter: MultiSampleCollectionAdapter
    private val model by viewModels<SingleViewModel>()
    private var isNFC = false
    private lateinit var replaceCaiXueDialog: ReplaceCaiXueDialog
    private var observable: Disposable? = null
    //前时间窗 秒
    private var preTimeMin = 0L
    //后时间窗 秒
    private var afterTimeMin = 0L
    private var planTime:Long = 0L
    private var orderId = 0
    private var checkCount = -1
    private var isAllChecked = false
    private var isCaiXue = false
    private var isReplace = false

    override fun init() {
        setTitle("样本采集")

        replaceCaiXueDialog = ReplaceCaiXueDialog(this)
        adapter = MultiSampleCollectionAdapter()
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false)
        recyclerView.adapter = adapter

        initClick()

        if(Build.MODEL == "V9100"){
            ScanUtils.init()
        }else{
            isNFC = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC)
            if(isNFC){
                NFCUtils(this)
            }
        }

        val drawbloodList = intent.getParcelableArrayListExtra<Drawblood>("bloodList")
        adapter.setNewInstance(drawbloodList)
        val it = drawbloodList!![0]
        tvName.text = it.patientInformation?.patientName
        tvSex.text = it.patientInformation?.patientSex
        tvCode.text = it.patientInformation?.urineRfidCode
        tvTubeName.text = it.drawbloodMoreOrder?.name
        orderId = it.drawbloodMoreOrder?.id?:0

        initView(it)
    }

    private fun initView(item: Drawblood) {
        preTimeMin = item.preTimeStamp?.toFloat()?.toLong() ?: 0L
        afterTimeMin = item.afterTimeStamp?.toFloat()?.toLong() ?: 0L

        val expectTime = item.expectTime
        tvPreTime.text = item.preTimeStamp
        tvAfterTime.text = item.afterTimeStamp
        tvPlanTime.text = expectTime
        //计划采血时间
        planTime = TimeUtils.string2Millis(expectTime, "yyyy-MM-dd HH:mm:ss")
        if (!isOver()) {
            //没超过计划时间
            val downTime = (afterTime - TimeUtils.getNowMills()) / 1000
            tvLJCY.text = "请立即采样"
            downTime(downTime)
        } else {
            //超窗  超过后时间窗  或者 没到前时间窗呢
            val currentTime = TimeUtils.getNowMills()
            if(currentTime < preTime){
               //还没到采血时间
                tvLJCY.text = "还未到采样时间"
                downTime((preTime - currentTime)/1000)
            }else{
                tvDownTime.text = "0"
            }
        }

        //多少根试管就添加多少个备注按钮和采血按钮
        adapter.data.forEach { item ->
            val remark = LayoutInflater.from(this).inflate(R.layout.include_remark_layout,null,false)
            val blood = LayoutInflater.from(this).inflate(R.layout.include_collection_blood_layout,null,false)
            remark.findViewById<TextView>(R.id.tvInputMark).text = "点击添加备注信息\n${item.name}"
            blood.findViewById<TextView>(R.id.tvStartTime).text = "点击记录采样时间\n${item.name}"

            remark.setOnClickListener {
                BloodRemarkDialog(this).show(item.otherRemark?:""){
                    //发送备注信息
                    showProgress()
                    model.updateDrawblood("${item.id}",it){
                        dismissProgress()
                        showToast("备注成功")
                    }
                }
            }

            //点击记录采血时间
            blood.setOnClickListener {
                if(!isAllChecked){
                    showToast("您还未完成核验")
                    return@setOnClickListener
                }
                val tvStartTime = blood.findViewById<TextView>(R.id.tvStartTime)
                if(tvStartTime.text.toString().contains("采血时间"))return@setOnClickListener

                if(isOver()){
                    //超窗,必须填写备注才可以记录采血时间
                    BloodRemarkDialog(this).show(item.otherRemark?:""){
                        val nowTime = TimeUtils.getNowString()
                        showProgress()
                        model.addRemarks(nowTime,"${item.id}",it){
                            dismissProgress()
                            tvStartTime.text = "采血时间:$nowTime\n${item.name}"
                            tvStartTime.setTextColor(getColor(R.color.color97))
                            collectBloodTime()
                        }
                    }
                }else{
                    //没有超窗  记录采血时间
                    showProgress()
                    model.bloodCollectionTime(TimeUtils.getNowString(), "${item.id}"){
                        dismissProgress()
                        tvStartTime.text = "采血时间:${TimeUtils.getNowString()}\n${item.name}"
                        tvStartTime.setTextColor(getColor(R.color.color97))
                        collectBloodTime()
                    }
                }

                adapter.data.find { it.checkSuccess != 4 }?.checkSuccess = 4
                adapter.notifyDataSetChanged()
            }

            llRemarks.addView(remark)
            llStartTime.addView(blood)
        }
    }

    /**'
     * 倒计时
     */
    private fun downTime(downTime:Long) {
        if(observable?.isDisposed != true){
            observable?.dispose()
        }
        tvDownTime.text = "$downTime"
        progress.setMaxProgress(downTime.toFloat())
        observable = Observable.interval(1, TimeUnit.SECONDS)
            .take(downTime)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { aLong: Long? ->
                tvDownTime.text = "${(downTime - aLong!!)}"
                progress.setProgress(aLong.toFloat())
            }
    }

    private fun initClick() {
        imgTH.setOnClickListener(this)
        tvStartCheck.setOnClickListener(this)
        imgJump.setOnClickListener(this)
        imgNext.setOnClickListener(this)
        imgScan.setOnClickListener(this)
    }
    private var afterTime = 0L
    private var preTime = 0L

    fun isOver():Boolean{
        val countTime = TimeUtils.getNowMills()
        preTime = planTime - preTimeMin*60*1000
        afterTime = planTime + afterTimeMin*60*1000
        //是否超窗
        return !(countTime > preTime && countTime < afterTime)
    }

    override fun onClick(v: View?) {
        when(v){
            //替换采血管
            imgTH -> {
                if(checkCount < 0){
                    showToast("请先点击核验")
                    return
                }
                isReplace = true
                /*replaceCaiXueDialog.show(adapter.data){ uid,position ->
                    isReplace = false
                    adapter.data[position].checkSuccess = 1
                    adapter.data[position].rfidCode = uid
                    adapter.notifyItemChanged(position)

                    checkCount--
                    if(checkCount == 0){
                        isAllChecked = true
                    }
                }*/
            }

            //开始核验
            tvStartCheck -> {
                groupHY.visibility = View.INVISIBLE
                val list = adapter.data
                checkCount = list.size
                tvYear.text = "${TimeUtils.getNowString(SimpleDateFormat("yyyy"))}\n${TimeUtils.getNowString(SimpleDateFormat("MM-dd"))}"
                ScanUtils.open {uid->
                    startCheck(uid, list)
                }
            }

            //紧急跳过
            imgJump -> {
                if(isCaiXue){
                    showToast("已采血，无法跳过")
                    return
                }
                showProgress()
                model.caixueJump("$orderId"){
                    dismissProgress()
                    imgStation.setBackgroundResource(R.drawable.icon_jjtg)
                    tvStation.text = "紧急跳过"
                    tvStation.setTextColor(getColor(R.color.orange))
                    progressGroup.visibility = View.GONE
                    groupHY.visibility = View.INVISIBLE
                    groupHYState.visibility = View.VISIBLE
                }
            }

            //下一个受试者
            imgNext -> {
                startActivity(NFCActivity::class.java)
                finish()
            }

            //扫描核验
            imgScan -> {
                startActivity(ScanZBarActivity::class.java)
                finish()
            }
        }
    }

    private fun collectBloodTime() {
        isCaiXue = true
        groupHYState.visibility = View.VISIBLE
        if (!isOver()) {
            //采血正常
            imgStation.setBackgroundResource(R.drawable.icon_heyan_success)
            tvStation.text = "采样正常"
        } else {
            imgStation.setBackgroundResource(R.drawable.icon_chaochuang)
            tvStation.text = "采样超窗"
            tvStation.setTextColor(getColor(R.color.red))
        }

        tvPlanCXTime.text = "计划采血时间:${tvPlanTime.text}"
        progressGroup.visibility = View.INVISIBLE
    }

    //开始核验
    private fun startCheck(uid: String, list: MutableList<Drawblood>) {
        if (isReplace) {
            replaceCaiXueDialog.setUID(uid)
            return
        }

        list.forEachIndexed { index, item ->
            if (uid == item.rfidCode) {
                checkCount--
                SoundUtils.playSound(SoundUtils.CHECK_SUCCESS)
                item.checkSuccess = 1
                item.scanTime = TimeUtils.getNowString(SimpleDateFormat("HH:mm:ss"))
                adapter.notifyItemChanged(index)
                if (checkCount == 0) {
                    isAllChecked = true
                    //全部核验完毕 记录核验时间
                    ScanUtils.close()
                    var id = ""
                    adapter.data.forEach {
                        if(id == ""){
                            id = "${it.id}"
                        }else{
                            id = "$id,${it.id}"
                        }
                    }
                    model.recordCheckTime(id){
                        showToast("已记录核验时间")
                    }
                }
                //核验正确 不往下走了
                return
            }
        }

        //核验错误，通过接口获取试管的名字，弹框提示
        showProgress()
        var noUid = ""
        adapter.data.forEach {
            if (noUid == "") {
                noUid = it.name?:"--"
            } else {
                noUid = "$noUid,${it.name}"
            }
        }
        model.searchName(arrayListOf(uid), {
            dismissProgress()
            BloodScanErrorDialog(this).show(noUid, it[0])
        }, {
            dismissProgress()
            showToast(it)
        })
        SoundUtils.playSound(SoundUtils.CHECK_ERROR)
    }

    override fun onResume() {
        super.onResume()
        if(!isNFC)return
        //开启前台调度系统
        NFCUtils.mNfcAdapter.enableForegroundDispatch(this,
            NFCUtils.mPendingIntent,
            NFCUtils.mIntentFilter, NFCUtils.mTechList)
    }

    override fun onPause() {
        super.onPause()
        if(!isNFC)return
        //关闭前台调度系统
        NFCUtils.mNfcAdapter.disableForegroundDispatch(this)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if(!isNFC)return
        //当该Activity接收到NFC标签时，运行该方法
        //调用工具方法，读取NFC数据
        var uid: String = NFCUtils.readNFCId(intent)
        uid = UIDUitls.sort(uid)
        startCheck(uid, adapter.data)
    }

    override fun onDestroy() {
        super.onDestroy()
        ScanUtils.onDestroy()
        observable?.dispose()
    }

}
